﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Ls.Utils;
using Ls.Web.Admin.Models;
using Ls.Web.Framework;
using Ls.Web.Admin.Areas.Sys.Models;

namespace Ls.Web.Admin.Controllers
{
    [Authorize]
    public class HomeController : BaseController
    { 
        public IActionResult Index()
        {
            return View();
        }

        public object Themes()
        {
            return AdminThemes.THEMEDIC.Select(kv => new { label = kv.Value, value = kv.Key }).ToList();
        } 
 
        [AllowAnonymous]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        [Route("Logout")]
        [AllowAnonymous]
        public async Task<ActionResult> Logout(string returnurl)
        {
            await AuthHelper.SingOutAsync();
            return Redirect(returnurl ?? "~/");
        }
        [Route("Login")]
        [AllowAnonymous]
        [HttpGet]
        public IActionResult Login()
        {
            ViewData["ReturnUrl"] = CommonHelper.ToString( Request.Query["ReturnUrl"]).IsNullOrEmpty()?"/": CommonHelper.ToString(Request.Query["ReturnUrl"]);
            return View();
        }

        [Route("Login")]
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> LoginAjaxAsync()
        {
            string username = Request.Form["username"];
            string password = Request.Form["password"];

            UserService userService = new UserService();
            SysLogService logService = new SysLogService();
            dynamic user = userService.Single("user_id,nickname,realname,username,userpwd,salt,is_sup", new   { username = username });
            if (user != null && user.userpwd == CryptoHelper.MD5(password+user.salt))
            {
                long user_id = CommonHelper.ToInt64(user.user_id);
                // 更新登录时间
                userService.Update(new { last_login_time = DateTime.Now, last_login_ip = HttpContext.GetUserIp() }, new { user_id = user_id });
                // 添加登录日志
                logService.Insert(new { 
                    user_id = user_id,
                    operation = "登录",
                    method = "LoginAjaxAsync",
                    opt_params =string.Format("用户【{0}】登录", user.realname),
                    create_id = user_id,
                    ip = HttpContext.GetUserIp(),
                    create_time = DateTime.Now
                });
                await AuthHelper.SignInAsync(user.user_id.ToString(), user.realname, CommonHelper.ToInt( user.is_sup));
                RemoveUserInfoCache(user_id);
                return Json(new { status = 200, message = "登录成功！" });
            }
            else
            {
                return Json(new { status = 300, message = "账号或者密码错误！" });
            }
        }
    }
}
